package com.yym.sina.weibo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Logger;

public class OAuthTokenGenerator {
	
	private static String authorizeURL;
	private static String accessTokenURL;
	private static String redirect_URI;
	private static String client_SERCRET;
	private static String client_ID;	
	
	private static final Logger log = Logger.getLogger(OAuthTokenGenerator.class.getName());
	
	static {
		authorizeURL = WeiboConfigLoader.getInstance().getValue("authorizeURL");
		accessTokenURL = WeiboConfigLoader.getInstance().getValue("accessTokenURL");
		redirect_URI = WeiboConfigLoader.getInstance().getValue("redirect_URI");
		client_SERCRET = WeiboConfigLoader.getInstance().getValue("client_SERCRET");
		client_ID = WeiboConfigLoader.getInstance().getValue("client_ID");		
	}	
	
	public static String constructAuthorizeUrl()
	{
		String url = authorizeURL+"?"
				+"client_id="+client_ID+"&"
				+"redirect_uri="+redirect_URI+"&"
				+"response_type=code";				
		return url;
	}
	
	public String getUserAccessToken(String code)
	{
		/**
		 * 3. 换取Access Token
		 *	https://api.weibo.com/oauth2/access_token
		 *  ?client_id=YOUR_CLIENT_ID
		 *  &client_secret=YOUR_CLIENT_SECRET
		 *  &grant_type=authorization_code
		 *  &redirect_uri=YOUR_REGISTERED_REDIRECT_URI
		 *  &code=CODE
		 */
		String accessToken = null;
		try {
			URL url = new URL(accessTokenURL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setUseCaches(false);
	        connection.setRequestMethod("POST");
	        connection.connect();
	        
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("client_id=" + client_ID
            		+"&"+"client_secret=" + client_SERCRET
            		+"&"+"grant_type=" + "authorization_code"
            		+"&"+"redirect_uri=" + redirect_URI
            		+"&"+"code=" + code
            );           
            writer.flush();
            writer.close();
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String jsonString = "";
            log.info("connection.getResponseCode()="+connection.getResponseCode());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
            	 String line;
                 while ((line = reader.readLine()) != null) {
                	 log.info(line);
                	 jsonString = jsonString + line;
                 }
                 reader.close();
                 accessToken = jsonString;
            } else {
                // Server returned HTTP error code.
            	System.out.println("error http code:"+connection.getResponseCode() );
            }
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/* GAE不支持
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod();
		NameValuePair[] data = 
		{ 
			new NameValuePair("client_id", client_ID),
			new NameValuePair("client_secret", client_SERCRET),
			new NameValuePair("grant_type", "authorization_code"),
			new NameValuePair("redirect_uri", redirect_URI),
			new NameValuePair("code", code)
		};
				
		postMethod.setRequestBody(data);
		// 执行postMethod
		try {
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) 
			{
			    System.err.println("Method failed: " + postMethod.getStatusLine());
			}
			//读取内容 
			byte[] responseBody = postMethod.getResponseBody();
			//处理内容
			String tmpString = new String(responseBody);
			System.out.println(tmpString);
			accessToken=tmpString;
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/
		
		return accessToken;
	}
	
}
